package interview.sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 选择排序
 * User: xxm
 * Date: 2018-03-31
 * Time: 23:31
 */
public class SelectionSort {

    public static int[] selectionSort(int[] array) {
        if (array.length == 0) {
            return array;
        }

        // 已排序 [1...i-1)
        for (int i = 0; i < array.length; i++) {
            int minIndex = i;
            // 未排序 [i...n)
            for (int j = i + 1; j < array.length; j++) {
                if (array[minIndex] > array[j]) {
                    minIndex = j;
                }
            }
            int temp = array[minIndex];
            array[minIndex] = array[i];
            array[i] = temp;
        }
        return array;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(
                SelectionSort.selectionSort(new int[]{0, -1, 2, -5, -20, -10})
        ));

        System.out.println(Arrays.toString(
                SelectionSort.selectionSort(new int[]{})
        ));

        System.out.println(Arrays.toString(
                SelectionSort.selectionSort(new int[]{4, 4, 4})
        ));

        System.out.println(Arrays.toString(
                SelectionSort.selectionSort(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9})
        ));

        System.out.println(Arrays.toString(
                SelectionSort.selectionSort(new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1})
        ));

        System.out.println(Arrays.toString(
                SelectionSort.selectionSort(new int[]{31, 50, 12, 44, 2, 55, 78, 43, 24})
        ));
    }
}